

import pandas as pd
from hashlib import md5
import requests
import json
import time
from flask import make_response


class login_inline():

    # 对密码进行加密
    def hashPwd(pwd):
        passwd = md5(pwd.encode(encoding='UTF-8')).hexdigest()
        return passwd

    # 获取系统token
    def get_token(self, base, name, password):
        headers = {"Content-Type":"application/json;charset=UTF-8","User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0"}
        login_url = "authority/auth/user/admin/login?"
        postData = {"loginName": name, "password": self.hashPwd(password)}
        url = base + login_url
        requests.packages.urllib3.disable_warnings()
        res = requests.post(url, headers=headers, data=json.dumps(postData), verify=False)
        result = eval(res.text)["responseData"]["token"]
        return result

    def with_draw(self, base_url, token, file_name):
        data = pd.read_excel(file_name, index=None)
        result_list = []
        error_list = []
        for i in range(len(data)):
            user_data = {}
            cardNo = str(data.loc[i]['卡号'])
            withdraw_amount = data.loc[i]['金额'].round(2)
            withdraw_clientSn = int(data.loc[i]['用户SN'])
            withdraw_name = data.loc[i]['姓名']

            param = {
                'cardNo': cardNo,
                'exchangeCode': '10000002',
                'withDrawAmount': withDrawAmount,
                'remark': '线下提现登记',
                'withDrawClientSn': withDrawClientSn,
                'adminAuthToken': token
            }
            url = base_url + "api/admin/offline/withdraw/order?"
            result = requests.get(url, params=param, verify=False)
            result = eval(result.text)
            if result['retCode'] != "0000":
                user_data["SN"] = withDrawClientSn
                user_data["姓名"] = withName
                user_data["金额"] = withDrawAmount
                user_data["错误信息"] = result["retMsg"]
                error_list.append(user_data)
                # print("登记结果为：{}".format(result['retMsg']))
                # print("*******************************************************************************************")
            # else:
                # print("登记结果为：提现登记成功")
                # print("*******************************************************************************************")
            result_list.append('SN：{0}, 姓名：{1} ,本次提现金额：{2}, 登记结果：{3} '.format(withDrawClientSn, withName, withDrawAmount, result))
            publick_meth().save_result(result_list)
        return result_list

    def exec_withdraw(self, base, user_name, passwd, file):
        if base == 'online':
            base_url = "https://invest.zfaex.com/"
        else:
            base_url = "http://192.168.33.112:9001/"
        try:
            token = self.get_token(base_url, user_name, passwd)
            if token:
                result = self.with_draw(base_url, token, file)
                return result
        except Exception as e:
            return e


class publick_meth():

    def save_result(self, result):
        path = 'result'
        file = time.strftime('%Y%m%d%H%M%S')+"_result.xlsx"
        if not os.path.exists(path):
            os.mkdir(path)
        file_name = os.path.join(path, file)
        data = pd.DataFrame(result)
        excelWriter = pd.ExcelWriter(file_name, engine='openpyxl')
        if os.path.exists(file_name) != True:
            data.to_excel(excel_writer=excelWriter, index=None)
            excelWriter.save()
            excelWriter.close()

    def return_result_file(self, file_type, file_name):
        basedir = os.path.abspath(os.path.dirname(__file__))
        # basedir一般是在配置文件中
        if file_name is None:
            return "未找到该文件！"
        file = open(os.path.join(basedir, '%s' % file_name), "rb").read()
        response = make_response(file)
        utf_filename = quote(file_name.encode("utf-8"))
        response.headers["Content-Disposition"] = "attachment;filename*=utf-8''{}".format(utf_filename)
        response.headers["Content-Type"] = "application/octet-stream; charset=UTF-8"
        return response
